﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using AhpilyServer.Concurrent;

namespace AhpilyServer
{
    /// <summary>
    /// 定时任务（计时器）管理类
    /// </summary>
    public class TimerManager //: Singleton<TimerManager>
    {
        #region 单例
        private static TimerManager _instance=null;
        public static TimerManager Instance
        {
            get {
                lock (_instance)
                {
                    if (_instance==null)
                    {
                        _instance = new TimerManager();
                    }
                    return _instance;
                }
            }
        }
        #endregion

        //实现定时器的主要功能就是这个Timer类
        private System.Timers.Timer timer;
        public int aa = 111;
        //这个字典存储：任务id 和 任务模型 的映射
        private ConcurrentDictionary<int, TimerModel> idModelDict = new ConcurrentDictionary<int, TimerModel>();

        private List<int> removeList = new List<int>();

        //用来表示id
        private ConcurrentInt id = new ConcurrentInt(-1);

        //TODO 任务每天奖励参数设置
        public TimerManager()
        {
            timer = new System.Timers.Timer(10);
            //达到间隔时发生(委托事件)
            timer.Elapsed += Timer_Elapsed;
        }

        //达到事件间隔时候触发
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (removeList)
            {
                TimerModel tmpModel = null;
                foreach (var id in removeList)
                {
                    //移除 把字典value提取出来
                    idModelDict.TryRemove(id, out tmpModel);
                }
                removeList.Clear();
            }
            

            foreach (var model in idModelDict.Values)
            {
                if(model.Time<=DateTime.Now.Ticks) model.run();
            }
        }

        /// <summary>
        /// 添加定时任务 指定触发的时间
        /// </summary>
        /// <param name="dateTime">表示时间上的一刻，通常以日期和当天的时间表示</param>
        /// <param name="timeDelegate"></param>
        public void AddTimerEvent(DateTime dateTime,TimeDelegate timeDelegate)
        {
            //一个延迟时间
            long delayTime = dateTime.Ticks - DateTime.Now.Ticks;
            
            //延迟时间不能小于0
            if (delayTime <= 0) return;

            AddTimerEvent(delayTime, timeDelegate);
      
        }

        /// <summary>
        /// 添加定时任务 指定延迟时间
        /// </summary>
        /// <param name="delayTime"></param>
        /// <param name="timeDelegate"></param>
        public void AddTimerEvent(long delayTime,TimeDelegate timeDelegate)
        {
            TimerModel model = new TimerModel(id.Add_Get(),DateTime.Now.Ticks+delayTime,timeDelegate);
            idModelDict.TryAdd(model.Id, model);
        }

    }
}
